import { defineAsyncComponent, type Component } from 'vue';
import { ElMessage } from 'element-plus';
import { v4 as uuidv4 } from 'uuid';
import { type CanvasComponent } from '@/stores/designStore';
import autoComponentLoader from '@/services/AutoComponentLoader';

// 组件注册表接口
interface ComponentRegistry {
  [key: string]: {
    name: string;           // 组件名称
    type: string;           // 组件类型标识符（用于拖拽）
    component: Component;   // Vue组件
    version: string;        // 组件版本
    category: string;       // 组件分类
    icon?: string;          // 显示图标
    description?: string;   // 描述
    author?: string;        // 作者
    preview?: string;       // 预览图片
    createdAt: Date;        // 创建时间
    isBuiltIn: boolean;     // 是否为内置组件
    path?: string;          // 本地组件路径(可选)
  };
}

// 组件加载结果
interface LoadComponentResult {
  success: boolean;
  message: string;
  componentId?: string;
}

class ComponentLoaderService {
  private registry: ComponentRegistry = {};
  private listeners: Array<(registry: ComponentRegistry) => void> = [];

  constructor() {
    // 初始化加载内置组件
    this.loadBuiltInComponents();
  }

  /**
   * 获取组件注册表
   */
  getRegistry(): ComponentRegistry {
    return { ...this.registry }; // 返回副本以防止外部修改
  }

  /**
   * 添加注册表变更监听器
   */
  addRegistryListener(listener: (registry: ComponentRegistry) => void): void {
    this.listeners.push(listener);
  }

  /**
   * 移除注册表变更监听器
   */
  removeRegistryListener(listener: (registry: ComponentRegistry) => void): void {
    const index = this.listeners.indexOf(listener);
    if (index !== -1) {
      this.listeners.splice(index, 1);
    }
  }

  /**
   * 通知所有监听器注册表已更新
   */
  private notifyListeners(): void {
    const registryCopy = { ...this.registry };
    this.listeners.forEach(listener => listener(registryCopy));
  }

  /**
   * 加载内置组件
   * 这些是应用内部已经存在的组件
   */
  private loadBuiltInComponents(): void {
    // 使用AutoComponentLoader获取组件映射
    autoComponentLoader.initialize().then((result: any) => {
      const { componentMap, componentCategories } = result;
      console.log('从AutoComponentLoader加载组件映射...');
      
      // 将自动扫描的组件注册到组件加载器中
      componentCategories.forEach(category => {
        category.components.forEach(comp => {
          const componentId = `builtin-${comp.type}`;
          this.registry[componentId] = {
            name: comp.text || comp.name,
            type: comp.type,
            component: defineAsyncComponent(() => import(`@/components/library/${category.key}/${comp.name}/index.vue`)),
            version: '1.0.0',
            category: category.key,
            icon: comp.icon || 'el-icon-component',
            description: `${category.title} - ${comp.text || comp.name}`,
            author: 'System',
            createdAt: new Date(),
            isBuiltIn: true
          };
        });
      });
      
      // 通知监听器
      this.notifyListeners();
    }).catch(error => {
      console.error('加载内置组件失败:', error);
    });
  }

  /**
   * 从本地文件加载组件
   * @param filePath 组件文件路径
   * @param options 组件配置选项
   */
  async loadComponentFromFile(filePath: string, options: {
    name: string;
    type: string;
    category: string;
    version?: string;
    icon?: string;
    description?: string;
    author?: string;
    preview?: string;
  }): Promise<LoadComponentResult> {
    try {
      // 验证必填选项
      if (!options.name || !options.type || !options.category) {
        return {
          success: false,
          message: '组件缺少必要信息：name、type和category是必填的'
        };
      }

      // 生成组件ID
      const componentId = `custom-${options.type}-${uuidv4().substring(0, 8)}`;

      // 验证是否已存在同名组件
      const existingComponent = Object.values(this.registry).find(c => 
        c.name === options.name || c.type === options.type
      );
      
      if (existingComponent) {
        return {
          success: false,
          message: `已存在同名组件：${options.name} 或同类型：${options.type}`
        };
      }

      // 使用动态导入加载组件
      const asyncComponent = defineAsyncComponent(() => {
        return new Promise((resolve, reject) => {
          import(/* @vite-ignore */ filePath)
            .then(module => {
              resolve(module.default || module);
            })
            .catch(error => {
              console.error('组件加载失败:', error);
              reject(new Error(`组件加载失败: ${error.message}`));
            });
        });
      });

      // 注册到组件库
      this.registry[componentId] = {
        name: options.name,
        type: options.type,
        component: asyncComponent,
        version: options.version || '1.0.0',
        category: options.category,
        icon: options.icon,
        description: options.description,
        author: options.author,
        preview: options.preview,
        createdAt: new Date(),
        isBuiltIn: false,
        path: filePath
      };

      // 通知监听器
      this.notifyListeners();

      return {
        success: true,
        message: `组件 ${options.name} 加载成功`,
        componentId
      };
    } catch (error) {
      console.error('组件加载错误:', error);
      return {
        success: false,
        message: `组件加载失败: ${error instanceof Error ? error.message : String(error)}`
      };
    }
  }

  /**
   * 卸载指定组件
   * @param componentId 组件ID
   */
  unloadComponent(componentId: string): boolean {
    if (!this.registry[componentId]) {
      return false;
    }

    // 内置组件不允许卸载
    if (this.registry[componentId].isBuiltIn) {
      ElMessage.warning(`${this.registry[componentId].name} 是内置组件，无法卸载`);
      return false;
    }

    delete this.registry[componentId];
    this.notifyListeners();
    return true;
  }

  /**
   * 创建可用于拖放系统的组件定义
   * @param componentId 组件ID
   */
  createComponentDefinition(componentId: string): { type: string; label: string; icon?: string } | null {
    const component = this.registry[componentId];
    if (!component) return null;

    return {
      type: component.type,
      label: component.name,
      icon: component.icon
    };
  }

  /**
   * 创建初始组件实例
   * @param componentId 组件ID
   */
  createInitialInstance(componentId: string): Partial<CanvasComponent> | null {
    const component = this.registry[componentId];
    if (!component) return null;

    return {
      type: component.type,
      props: {},
      style: {
        position: 'absolute',
        width: '100px',
        height: '32px'
      }
    };
  }
}

// 创建单例实例
const componentLoader = new ComponentLoaderService();

export default componentLoader;

/**
 * 动态加载组件的导出处理模块
 * @param componentType 组件类型
 * @returns 导出处理模块或null
 */
export async function loadComponentExport(componentType: string) {
  try {
    // 使用AutoComponentLoader加载组件导出处理模块
    return await autoComponentLoader.loadComponentExport(componentType);
  } catch (error) {
    console.error(`加载组件(${componentType})导出处理模块失败:`, error);
    return null;
  }
} 